 /**
 * 逻辑、功能相关描述:
 *
 * @author yandawei 编写日期：2008-10-20
 */
package com.ce.pms.common.aop.impl;

import java.util.List;

import org.apache.log4j.Logger;

import com.ce.pms.common.annotation.AssociatedPrecinctParameter;
import com.ce.pms.common.dao.IDataRightDao;
import com.ce.pms.exception.DaclUnsupportedParameterException;
import com.ce.util.BlankUtil;
import com.ce.util.CurrentUserThread;

/**
 * @author yandawei
 *
 */
public aspect AssociatePrecinctParameterAdvice {
	private IDataRightDao dataRightDao;



	public IDataRightDao getDataRightDao() {
		return dataRightDao;
	}

	public void setDataRightDao(IDataRightDao dataRightDao) {
		this.dataRightDao = dataRightDao;
	}
	private Logger log =  Logger.getLogger(AssociatePrecinctParameterAdvice.class);

	pointcut associatedPrecinctParameter(AssociatedPrecinctParameter anno): execution(* *(..))&& @annotation(anno);

	before(AssociatedPrecinctParameter anno):execution(@AssociatedPrecinctParameter * *(..))&& @annotation(anno){
		log.info("===DACL===");

		Long userId = CurrentUserThread.get().getUserId();
		Long id = null;
		int  precinctIndex = anno.precinctIndex();

		Class clazz = anno.clazz();

		int associatedPrecinctIndex= anno.associatedPrecinctIndex();

		Object[] args = thisJoinPoint.getArgs();
		Object obj = args[associatedPrecinctIndex];
		if(obj instanceof Long){
			id = (Long)obj;
		}else{
			throw new DaclUnsupportedParameterException("不支持的参数!");
		}

		String property4PrecinctID = anno.property4PrecinctID();

		String property4AssociatedPrecinctID = anno.property4AssociatedPrecinctID();

		System.out.println("检验访问相关主键为"+obj.toString()+"记录权限...");
		StringBuffer sql = new StringBuffer("select * from  "+clazz.getName()+" alias where ") ;
		if(!BlankUtil.isBlank(property4AssociatedPrecinctID)){
			sql.append("alias."+property4AssociatedPrecinctID+"=? and");
		}
		sql.append(" alias."+property4PrecinctID+".keyword in (select secRight.resourceId from SecUserRelationRight secRight where secRight.employeeDO.employeeId= ?)");
		List list = dataRightDao.findAllResult(sql.toString(), new Long[]{id,userId});
		if(list.size() <=0){
			throw new DaclUnsupportedParameterException("数据权限不足,不能访问!");
		}

	}
}
